package edu.ujf.sharepas.rcp.actions;

import java.rmi.RemoteException;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;

import edu.ujf.sharepas.impl.Category;
import edu.ujf.sharepas.impl.Constante;
import edu.ujf.sharepas.impl.Friend;
import edu.ujf.sharepas.impl.User;
import edu.ujf.sharepas.rcp.Activator;
import edu.ujf.sharepas.rmi.Client;

public class AddFileAction extends Action {

	private User me;
	private ISelectionProvider provider; 
	private Category cat ;
	
	public AddFileAction(ISelectionProvider selectionProvider, User me, String label ) {
		this.provider = selectionProvider;
		this.me = me;
        setText(label);
        // The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_ADDFILE);
        // Associate the action with a pre-defined command, to allow key bindings.
		setActionDefinitionId(ICommandIds.CMD_ADDFILE);
		setImageDescriptor(edu.ujf.sharepas.rcp.Activator.getImageDescriptor("/icons/sample2.gif"));
	}
	
	public boolean isEnabled() {
		ISelection selection = provider.getSelection();
		if(!selection.isEmpty()) {
			IStructuredSelection sSelection = (IStructuredSelection) selection;
			if(sSelection.size() == 1 && 
			   sSelection.getFirstElement() instanceof Category) 
			{
				cat = ((Category)sSelection.getFirstElement()); 				
				return true;
			}
		}
		return false;
	}
	
	public void run() {
		if(isEnabled()){
			final Shell shell = new Shell(Display.getDefault());
			FileDialog dlg = new FileDialog(shell, SWT.OPEN);
		
			if((Constante.CategoryType.VIDEO).toInt() == cat.getType()){
				dlg.setFilterNames(Constante.VIDEO_FILTER_NAMES);
				dlg.setFilterExtensions(Constante.VIDEO_FILTER_EXTS);
			}else if((Constante.CategoryType.AUDIO).toInt() == cat.getType()){
				dlg.setFilterNames(Constante.AUDIO_FILTER_NAMES);
				dlg.setFilterExtensions(Constante.AUDIO_FILTER_EXTS);
			}else if((Constante.CategoryType.PHOTO).toInt() == cat.getType()){
				dlg.setFilterNames(Constante.PHOTO_FILTER_NAMES);
				dlg.setFilterExtensions(Constante.PHOTO_FILTER_EXTS);
			}else if((Constante.CategoryType.DOC).toInt() ==cat.getType()){
				dlg.setFilterNames(Constante.DOC_FILTER_NAMES);
				dlg.setFilterExtensions(Constante.DOC_FILTER_EXTS);
			}else{
				dlg.setFilterNames(Constante.DOC_FILTER_NAMES);
				dlg.setFilterExtensions(Constante.DOC_FILTER_EXTS);
			}

			String fileName = dlg.open();
		    if(fileName != null){
		    	me.addFile(fileName, cat,Constante.Right.WRITE);
		    }
		
		}
	}
	
	
}
